<template>
  <div class="screen-container" :style="{ backgroundColor: bgColor }">
    <div class="screen-top">
      <screenfull id="screenfull" class="screen-full hover-effect" @onScreenfull="handleScreenFull" />
      <div>
        <el-button v-show="showMenu" class="fix-btn num-btn" size="large" type="" @click="dialogNumVisible = true">设置号牌</el-button>
        <el-button v-show="showMenu" class="fix-btn screen-btn" size="large" type="" @click="dialogRateVisible = true">设置汇率</el-button>
        <el-color-picker v-show="showMenu" v-model="bgColor" class="fix-btn color-btn" :predefine="predefineColors" />
      </div>
    </div>

    <el-row class="screen-main" :gutter="0">
      <el-col :xs="10" :sm="10" :md="10" :lg="10" class="screen-main-left">
        <div class="goods-title">Lot {{ curr.lot }}：{{ curr.name }}</div>
        <div class="goods-price">
          <div class="goods-price-item">
            <span>起拍价</span> <b>{{ toThousands(curr.start) }}</b>
          </div>
          <div class="now-time">{{ dateFormat(date) }}</div>
          <div class="goods-price-item red">
            <span>底价</span> <b>{{ toThousands(curr.resr_price) }}</b>
          </div>
        </div>
        <div class="goods-cover">
          <img :src="curr.cover" alt="">
        </div>
      </el-col>
      <el-col :xs="14" :sm="14" :md="14" :lg="14" class="screen-main-right">
        <div class="bids-last">
          <div v-for="(item, index) in bids" :key="index" class="bids-last-item">
            <span>{{ item.way }}</span>
            <span :class="speNums.indexOf(item.num.toString()) > -1 ? 'rednum': ''">{{ item.num }}</span>
            <span>{{ toThousands(item.bid) }}</span>
          </div>
        </div>
        <el-divider />
        <el-row :gutter="30" class="bids-curr">
          <el-col :xs="24" :sm="24" :md="14" :lg="14" class="bids-curr-box">
            <div class="bids-curr-item"><label class="label">JPY</label><b> {{ toThousands(curr.curr) }}</b></div>
            <div class="bids-curr-item small"><span class="label">RMB</span> {{ toThousands(rateVal.rmb ) || '未设置汇率' }}</div>
            <div class="bids-curr-item small"><span class="label">HKD</span> {{ toThousands(rateVal.hkd ) || '未设置汇率' }}</div>
            <div class="bids-curr-item small"><span class="label">USD</span> {{ toThousands(rateVal.usd ) || '未设置汇率' }}</div>
          </el-col>
          <el-col :xs="24" :sm="24" :md="10" :lg="10" class="broadcast">
            <img src="@/assets/icon-broadcast-white.png" alt="">{{ broadcastMsg }}
          </el-col>
        </el-row>
      </el-col>
    </el-row>

    <div class="screen-btm">
      <div><span>共 {{ num[0] }} 件</span><span>已拍 {{ num[1] + num[2] }} 件</span><span>剩余 {{ num[3] }} 件</span></div>
      <span v-show="last">上一件 Lot {{ last.lot }} &nbsp; {{ last.state }} &nbsp; 最后出价：{{ toThousands(last.bid) }}</span>
    </div>

    <el-dialog title="请选择专场" :close-on-press-escape="false" :show-close="false" :close-on-click-modal="false" center :visible.sync="dialogTableVisible">
      <el-table
        v-loading="listLoading"
        :data="lotList"
        element-loading-text="Loading"
        height="350"
        @row-click="handleRowClick"
      >
        <el-table-column property="id" label="ID" width="100" />
        <el-table-column property="name" label="专场名称" show-overflow-tooltip max-width="400" />
      </el-table>
    </el-dialog>
    <el-dialog title="设置汇率" center :visible.sync="dialogRateVisible" @closed="handleRateClosed">
      <el-form :model="rate" label-position="left">
        <el-form-item label="RMB" label-width="50px">
          <el-input v-model="rate.rmb" :min="0" type="number" autocomplete="off" />
        </el-form-item>
        <el-form-item label="HKD" label-width="50px">
          <el-input v-model="rate.hkd" :min="0" type="number" autocomplete="off" />
        </el-form-item>
        <el-form-item label="USD" label-width="50px">
          <el-input v-model="rate.usd" :min="0" type="number" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogRateVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSetRate">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="设置号牌" center :visible.sync="dialogNumVisible" @closed="handleNumClosed">
      <el-form :model="speNums" style="text-align:center" label-width="80px">
        <el-form-item
          v-for="(item, index) in speNums"
          :key="index"
          :label="'号牌' + index"
          style="max-width:450px;margin: 10px auto"
        >
          <el-row :gutter="10">
            <el-col :span="18">
              <el-input v-model.trim="speNums[index]" />
            </el-col>
            <el-col :span="4" offset>
              <el-button @click.prevent="removeSpeNum(item, index)">删除</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item style="margin-left:-80px">
          <el-button type="primary" @click="addSpeNum">新增号牌</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogNumVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSetNum">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Screenfull from '@/components/Screenfull'
import { getScreenLots, getScreenData } from '@/api/ctrl'
import { toThousands } from '@/utils'

export default {
  components: { Screenfull },
  data () {
    return {
      lotId: '',
      listLoading: false,
      lotList: [],
      name: '',
      num: [0, 0, 0, 0],
      curr: {
        spec: []
      },
      last: false,
      bids: [],
      dialogTableVisible: false,
      dialogRateVisible: false,
      dialogNumVisible: false,
      rate: {
        rmb: 0,
        hkd: '',
        usd: ''
      },
      speNums: [''],
      h5Qr: '',
      showMenu: true,
      bgColor: '#333333',
      predefineColors: ['#333333', '#415E8F'],
      date: new Date(),
      broadcastMsg: '中场休息20分钟'
    }
  },
  computed: {
    rateVal () {
      var data = {
        rmb: '',
        hkd: '',
        usd: ''
      }
      for (var key in this.rate) {
        if (this.rate[key]) {
          if (!isNaN(this.curr.curr)) {
            data[key] = Math.round(this.rate[key] * Number(this.curr.curr))
          } else {
            data[key] = this.curr.curr
          }
        }
      }
      return data
    }
  },
  watch: {
    $route () {
      const id = this.$route.query && this.$route.query.id
      if (!id) {
        this.fetchLots()
        this.dialogTableVisible = true
      } else {
        this.fetchData()
        this.wsSendMsg('join')
      }
    }
  },
  created () {
    const id = this.$route.query && this.$route.query.id
    this.lotId = id
    this.initWebSocket()
    const rateData = JSON.parse(window.localStorage.getItem('auc_ctrl_rate'))
    if (rateData) {
      this.rate = rateData
    }
    const speNumData = JSON.parse(window.localStorage.getItem('auc_ctrl_spenum'))
    if (speNumData) {
      this.speNums = speNumData
    }
    if (!id) {
      this.fetchLots()
    } else {
      this.fetchData()
    }
  },
  mounted () {
    console.log(this.orientation)
    document.addEventListener('visibilitychange', this.handleVisiable)
    this.timer = setInterval(() => {
      this.date = new Date()
    }, 1000)
    // 监听横竖屏
    window.addEventListener('orientationchange', () => {
      console.log(window.orientation)
      if (window.orientation === 0 || window.orientation === 180) {
        console.log('portrait')
      }
    })
  },
  beforeDestroy () {
    if (this.timer) {
      clearInterval(this.timer)
    }
  },
  destroyed () {
    // this.wsSendMsg('leave')
  },
  methods: {
    handleVisiable (e) {
      if (e.target.visibilityState === 'visible') {
        if (!this.global.wsConnected) {
          this.initWebSocket()
        }
      }
    },
    fetchData () {
      this.listLoading = true
      getScreenData(this.lotId).then(res => {
        this.name = res.data.name
        this.num = res.data.num
        this.curr = res.data.curr
        this.last = res.data.last
        this.bids = res.data.bids
        this.h5Qr = res.data.h5Qr
        this.listLoading = false
      }).catch(err => {
        console.log(err)
        this.listLoading = false
      })
    },
    fetchLots () {
      this.listLoading = true
      this.dialogTableVisible = true
      getScreenLots().then(res => {
        this.lotList = res.data
        this.total = res.data.total
        this.listLoading = false
      }).catch(err => {
        console.log(err)
        this.listLoading = false
      })
    },
    handleRowClick (row) {
      this.lotId = row.id
      this.$router.push(`/aucer?id=${row.id}`)
      this.dialogTableVisible = false
    },
    handleSetRate () {
      window.localStorage.setItem('auc_ctrl_rate', JSON.stringify(this.rate))
      this.dialogRateVisible = false
    },
    handleRateClosed () {
      const rateData = JSON.parse(window.localStorage.getItem('auc_ctrl_rate'))
      if (rateData) {
        this.rate = rateData
      } else {
        this.rate = {
          rmb: '',
          hkd: '',
          usd: ''
        }
      }
    },
    addSpeNum () {
      this.speNums.push('')
    },
    removeSpeNum (item, index) {
      this.speNums.splice(index, 1)
    },
    handleSetNum () {
      window.localStorage.setItem('auc_ctrl_spenum', JSON.stringify(this.speNums))
      this.dialogNumVisible = false
    },
    handleNumClosed () {
      const speNumData = JSON.parse(window.localStorage.getItem('auc_ctrl_spenum'))
      if (speNumData) {
        this.speNums = speNumData
      } else {
        this.speNums = ['']
      }
    },
    initWebSocket () {
      const wsData = {
        type: 'join',
        lot_id: this.lotId
      }
      if (this.global.ws) {
        if (this.global.wsConnected) {
          this.global.ws.send(JSON.stringify(wsData))
        }
      } else {
        this.global.ws = new WebSocket(process.env.VUE_APP_WS_HOST)
        this.global.setWs(this.global.ws)
      }
      this.global.ws.onopen = this.wsOnOpen
      this.global.ws.onerror = this.wsOnError
      this.global.ws.onmessage = this.wsOnMessage
      this.global.ws.onclose = this.wsOnClose
    },
    wsOnMessage (e) {
      var data = JSON.parse(e.data)
      // console.log(data)
      const arr = ['willHammer', 'faceLive', 'startAuc', 'cancelAuc', 'dealAuc', 'passAuc', 'reAuc', 'liveBid', 'netBid', 'phoneBid', 'broadcast']
      if (Number(data.lot_id) === Number(this.lotId)) {
        switch (true) {
          // 进入、离开专场
          case data.type === 'join' || data.type === 'leave':
            console.log(`${data.uid} ${data.type} 专场 ${this.lotId}`)
            break
          case data.type === 'end':
            this.$alert('本专场已结束', {
              confirmButtonText: '关闭',
              callback: action => {
                this.$router.push(`/screen`)
              }
            })
            break
          case data.type === 'count':
            console.log('更新统计数据！')
            this.num = data.num
            break
          case arr.indexOf(data.type) > -1:
            if (data.type === 'broadcast') {
              this.broadcastMsg = data.msg
            }
            if (data.goods || data.goods === false) {
              this.curr = data.goods
            }
            if (data.last || data.last === false) {
              this.last = data.last
            }
            if (data.type === 'startAuc' || data.type === 'reAuc') {
              this.bids = []
            }
            if (data.type === 'dealAuc') {
              this.$message({
                dangerouslyUseHTMLString: true,
                type: 'success',
                center: true,
                message: `<strong style="font-size: 2vw">${data.msg}</strong>`
              })
            }
            break
          // 出价更新出价列表 撤销出价
          case data.type === 'bid' || data.type === 'revoke':
            var { num, bid } = data
            var way = Number(num) === 0 ? '现场' : '网络'
            this.curr.curr = bid
            if (data.type === 'bid') {
              if (this.bids.length >= 2) {
                this.bids.pop()
              }
              this.bids.unshift({ num, bid, way })
            } else {
              this.bids.shift()
            }
            break
        }
      }
    },
    wsOnOpen () {
      console.log('组件内WebSocket连接成功!')
      this.global.wsConnected = true
      this.wsSendMsg('join')
    },
    wsOnError (e) {
      console.log('组件内WebSocket连接发生错误!')
      this.global.wsConnected = false
    },
    wsOnClose () {
      console.log('组件内WebSocket连接关闭!')
      this.global.wsConnected = false
      this.global.ws = new WebSocket(process.env.VUE_APP_WS_HOST)
      this.global.setWs(this.ws)
    },
    wsSendMsg (type) {
      if (this.global.ws && this.global.wsConnected) {
        var msg = {
          type,
          lot_id: this.lotId
        }
        this.global.ws.send(JSON.stringify(msg))
      }
    },
    toThousands,
    handleScreenFull (val) {
      this.showMenu = val
    },
    dateFormat (time) {
      var date = new Date(time)
      var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
      var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      // 拼接
      return hours + ':' + minutes + ':' + seconds
    }
  }
}
</script>

<style lang="scss" scoped>
$topHeight: calc(32px + 1.4vw);
$mainHeight: calc(100vh - 110px - 3.15vw);

.screen-container {
  height: 100vh;
  background: #333;
  color: #fff;
  .screen-top {
    display: flex;
    align-items: center;
    padding: 15px;
    justify-content: space-between;
    .fix-btn {
      font-size: 1.4vw;
      height: $topHeight;
    }
    .screen-full {
      display: inline-block;
      font-size: calc(20px + 1.4vw);
      line-height: $topHeight;
      color: #fff;
      &.hover-effect {
        cursor: pointer;
        transition: background .3s;
        &:hover {
          background: rgba(0, 0, 0, .025)
        }
      }
    }
    &>div {
      display: flex;
      align-items: center;
      /deep/.el-color-picker {
        padding: 0;
        margin-left: 10px;
        width: $topHeight;
        height: $topHeight;
        &__trigger {
          width: 100%;
          height: 100%;
          background: #fff;
        }
      }
    }
  }
  .screen-btm {
    width: 100vw;
    position: fixed;
    bottom: 0;
    font-size: 1.75vw;
    padding: 20px 15px;
    display: flex;
    justify-content: space-around;
  }
  .screen-main {
    height: $mainHeight;
    &-left {
      color: #000;
      height: 100%;
      background: #fff;
      font-weight: 600;
      padding: 20px 40px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      .goods-title {
        text-align: center;
        overflow: hidden;
        text-overflow:ellipsis;
        white-space: nowrap;
        font-size: 1.75vw;
        margin: 25px 0;
        padding: 0 20px;
      }
      .goods-price {
        font-size: 1.35vw;
        margin: 20px 0;
        display: flex;
        align-items: center;
        justify-content: space-between;
        &-item {
          display: flex;
          flex-direction: column;
          align-items: center;
        }
      }
      .goods-cover {
        width: 24vw;
        height: 24vw;
        margin: 30px auto;
        img {
          width: 100%;
          height: 100%;
          display: block;
        }
      }
    }
    &-right {
      height: 100%;
      display: flex;
      padding: 4vw 5vw;
      flex-direction: column;
      justify-content: center;
      background: rgb(0, 87, 248);
      .bids-last {
        // height: 100%;
        font-size: 3.5vw;
        font-weight: 500;
        &-item {
          line-height: 1.5;
          display: flex;
          align-items: center;
          span {
            width: 27%;
            text-align: center;
            &:first-of-type {
              text-align: left;
            }
            &:last-of-type {
              width: 45%;
              text-align: right;
            }
          }
        }
      }
      .bids-curr {
        // height: 100%;
        &-item {
          display: flex;
          justify-content: space-between;
          font-size: 3vw;
          line-height: 2;
          &.small {
            font-size: 1.9vw;
          }
        }
      }
      /deep/.el-divider {
        margin: 45px 0 35px;
      }
    }
  }
  .now-time {
    font-size: 2.5vw;
    font-weight: bold;
    color: #DA8928;
  }
  .red {
    color: red;
  }
  .rednum {
    color: rgb(247, 99, 99);
    color: #EFFA0C;
  }
  .broadcast {
    height: 100%;
    font-size: 2vw;
    line-height: 1.5;
    display: flex;
    align-items: center;
    img {
      width: 3vw;
      margin-right: 5px;
    }
  }
  .el-table:hover {
    cursor: pointer;
  }
  @media screen and (max-width: 1500px) {}
}
</style>
